﻿using PLCS.App.Shared.Service;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.StationApp.Dtos;
using PLCS.Client.IService.LogManager;
using PLCS.Domain.Equipments;
using PLCS.Shared.Common.Constant;

namespace PLCS.App.EquipmentManager.ViewModels.Station;

public class StationDetailViewModel : HostDialogViewModel
{
    public StationDetailViewModel(IObjectMapper<EquipmentManagerModule> objectMapper, IStationService stationService, IOperationLogService logShowService, CacheSettingService cacheSettingService)
    {
        this._objectMapper = objectMapper;
        this._stationService = stationService;
        this._logShowService = logShowService;
        _cacheSettingService = cacheSettingService;
        View = "工位管理弹窗";
    }

    private StationDto _model;
    private readonly IObjectMapper<EquipmentManagerModule> _objectMapper;
    private readonly IStationService _stationService;
    private readonly IOperationLogService _logShowService;
    private readonly CacheSettingService _cacheSettingService;

    public StationDto Model
    {
        get { return _model; }
        set { _model = value; }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var station = _objectMapper.Map<StationDto, StationEditDto>(Model);
            station.AreaNo = _cacheSettingService.cacheSetting.AreaNo;
            station.SiteNo = _cacheSettingService.cacheSetting.SiteNo;
            station.PdLineNo = _cacheSettingService.cacheSetting.PdLineNo;
            if (station.Id != Guid.Empty)
            {
                Log("修改", station);
                await _stationService.UpdateAsync(station);
            }
            else
            {
                Log("新增", station);
                await _stationService.CreateAsync(station);
            }

            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally { SavebuttonIsEnabled = true; }
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<StationDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new StationDto();
        }
    }
}